// 等待 DOM 加载完成
document.addEventListener('DOMContentLoaded', function () {
    // 初始化数量增减功能
    initQuantitySelector();

    // 初始化支付方式
    initPaymentMethods();
    // 初始化复制订单号功能
    initCopyOrderNum();

    // 绑定立即购买按钮事件
    document.querySelector('.btn-buy').addEventListener('click', function () {
        const productId = document.querySelector('.product-id').textContent.replace('编号:', '').trim();
        const quantity = parseInt(document.querySelector('.quantity-input').value);
        const price = parseFloat(document.querySelector('.current-price').textContent.replace('¥', '').replace('元/份', '').trim());
        const totalAmount = price * quantity;

        // 设置支付金额
        document.querySelector('.payment-amount span').textContent = '¥' + totalAmount.toFixed(1);
        // 生成随机订单号
        const orderNum = 'WC' + new Date().getTime() + Math.floor(Math.random() * 1000);
        document.querySelector('.payment-instructions input').value = orderNum;

        // 显示支付模态框
        const paymentModal = new bootstrap.Modal(document.getElementById('paymentModal'));
        paymentModal.show();

        // 重置支付状态
        document.getElementById('paymentSuccess').classList.add('d-none');
        document.getElementById('paymentFailed').classList.add('d-none');
    });

    // 绑定加入购物车按钮事件
    document.querySelector('.btn-cart').addEventListener('click', function () {
        const productId = document.querySelector('.product-id').textContent.replace('编号:', '').trim();
        const productName = document.querySelector('.product-title').textContent.trim();
        const quantity = parseInt(document.querySelector('.quantity-input').value);
        const price = parseFloat(document.querySelector('.current-price').textContent.replace('¥', '').replace('元/份', '').trim());
        const imageSrc = document.querySelector('.carousel-item.active img').src;

        // 获取购物车数据或初始化空数组
        let cartItems = JSON.parse(localStorage.getItem('cartItems')) || [];

        // 检查商品是否已在购物车中
        const existingItemIndex = cartItems.findIndex(item => item.id === productId);

        if (existingItemIndex >= 0) {
            // 如果已存在，增加数量
            cartItems[existingItemIndex].quantity += quantity;
        } else {
            // 如果不存在，添加新商品
            cartItems.push({
                id: productId,
                name: productName,
                price: price,
                quantity: quantity,
                image: imageSrc
            });
        }

        // 保存到本地存储
        localStorage.setItem('cartItems', JSON.stringify(cartItems));

        // 显示成功提示
        showAlert('success', '商品已成功加入购物车！');
    });

    // 绑定支付模态框显示事件
    document.getElementById('paymentModal').addEventListener('shown.bs.modal', function () {
        // 每次显示模态框时重置支付状态
        document.getElementById('paymentSuccess').classList.add('d-none');
        document.getElementById('paymentFailed').classList.add('d-none');
    });

    // 绑定支付模态框确认按钮事件
    document.querySelector('.modal-footer .btn-secondary').addEventListener('click', function () {
        // 取消支付逻辑
        console.log('用户取消了支付');
    });
});

// 初始化数量选择器
function initQuantitySelector() {
    document.querySelector('.minus').addEventListener('click', function () {
        const input = document.querySelector('.quantity-input');
        if (input.value > 1) {
            input.value--;
        }
    });

    document.querySelector('.plus').addEventListener('click', function () {
        const input = document.querySelector('.quantity-input');
        input.value++;
    });

    // 确保输入的值是有效的
    document.querySelector('.quantity-input').addEventListener('change', function () {
        if (this.value < 1 || isNaN(this.value)) {
            this.value = 1;
        }
    });
}

// 初始化支付方式
function initPaymentMethods() {
    document.querySelectorAll('.list-group-item').forEach(item => {
        item.addEventListener('click', function (e) {
            e.preventDefault();

            // 更新活跃状态
            document.querySelector('.list-group-item.active').classList.remove('active');
            this.classList.add('active');

            // 获取支付方式
            const method = this.dataset.method;
            const amount = parseFloat(document.querySelector('.payment-amount span').textContent.replace('¥', ''));
            const orderNum = document.querySelector('.payment-instructions input').value;

            // 更新支付信息
            updatePaymentInfo(amount, orderNum, method);
        });
    });
}

// 更新支付信息
function updatePaymentInfo(amount, orderNum, method) {
    let methodName = '';
    let qrData = '';
    let instructions = '';

    switch (method) {
        case 'alipay':
            methodName = '支付宝';
            qrData = `https://alipay.com/pay?amount=${amount}&orderNum=${orderNum}`;
            instructions = '请使用支付宝扫描二维码完成支付';
            break;
        case 'wechatpay':
            methodName = '微信支付';
            qrData = `weixin://wxpay/bizpayurl?amount=${amount}&orderNum=${orderNum}`;
            instructions = '请使用微信扫描二维码完成支付';
            break;
        case 'bankcard':
            methodName = '银行卡支付';
            qrData = `bank://pay?amount=${amount}&orderNum=${orderNum}`;
            instructions = '请输入您的银行卡信息完成支付';
            break;
    }

    // 更新 UI
    document.getElementById('currentMethod').textContent = methodName;
    document.getElementById('paymentInstructions').textContent = instructions;
    document.getElementById('qrCodeImage').src = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qrData)}`;

    // 如果是银行卡支付，隐藏二维码区域
    if (method === 'bankcard') {
        document.querySelector('.qr-code-container').classList.add('d-none');
        document.getElementById('paymentInstructions').textContent = '请输入您的银行卡信息完成支付';
    } else {
        document.querySelector('.qr-code-container').classList.remove('d-none');
    }

    // 模拟支付检查
    simulatePaymentCheck();
}

// 初始化复制订单号功能
function initCopyOrderNum() {
    const copyBtn = document.getElementById('copyOrderNum');
    if (copyBtn) {
        copyBtn.addEventListener('click', function () {
            const orderNumInput = document.querySelector('.payment-instructions input');
            orderNumInput.select();
            document.execCommand('copy');

            // 显示复制成功提示
            const originalText = this.innerHTML;
            this.innerHTML = '<i class="bi bi-check"></i> 已复制';
            setTimeout(() => {
                this.innerHTML = originalText;
            }, 2000);
        });
    }
}

// 模拟支付状态检查
function simulatePaymentCheck() {
    // 重置支付状态显示
    document.getElementById('paymentSuccess').classList.add('d-none');
    document.getElementById('paymentFailed').classList.add('d-none');

    setTimeout(() => {
        // 随机模拟支付成功或失败
        const isSuccess = Math.random() > 0.3;

        if (isSuccess) {
            document.getElementById('paymentSuccess').classList.remove('d-none');
            document.getElementById('paymentFailed').classList.add('d-none');

            // 3 秒后自动关闭模态框
            setTimeout(() => {
                const paymentModal = bootstrap.Modal.getInstance(document.getElementById('paymentModal'));
                paymentModal.hide();
                showAlert('success', '支付成功！感谢您的购买！');
            }, 3000);
        } else {
            document.getElementById('paymentSuccess').classList.add('d-none');
            document.getElementById('paymentFailed').classList.remove('d-none');
        }
    }, 3000);
}

// 显示提示信息
function showAlert(type, message) {
    // 移除现有的提示
    const existingAlert = document.querySelector('.custom-alert');
    if (existingAlert) {
        existingAlert.remove();
    }

    // 创建新的提示元素
    const alertDiv = document.createElement('div');
    alertDiv.className = `custom-alert alert alert-${type} fixed-top w-100 text-center`;
    alertDiv.style.zIndex = '9999';
    alertDiv.style.top = '56px'; // 在导航栏下方
    alertDiv.textContent = message;

    document.body.appendChild(alertDiv);

    // 3 秒后自动消失
    setTimeout(() => {
        alertDiv.remove();
    }, 3000);
}